package cn.wen233.orderconsumer.config;

import cn.wen233.common.infrustructure.exception.BaseException;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.lang.reflect.Type;

/**
 * feign异常处理
 *
 * @author wenei
 * @date 2021-06-08 9:09
 */
@Component
public class FeignConfiguration implements Decoder {

    private static final Logger log = LoggerFactory.getLogger(FeignConfiguration.class);

    private final ObjectFactory<HttpMessageConverters> httpMessageConvertersObjectFactory;

    private SpringDecoder decoder;

    public FeignConfiguration(ObjectFactory<HttpMessageConverters> httpMessageConvertersObjectFactory) {
        this.httpMessageConvertersObjectFactory = httpMessageConvertersObjectFactory;
    }

    @PostConstruct
    public void init() {
        decoder = new SpringDecoder(httpMessageConvertersObjectFactory);
    }

    /**
     * 将服务提供方的数据获取后，判断其status是否为200
     */
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        if (response.status() != HttpStatus.OK.value()) {
            log.warn("服务回调解码时的body():" + response.body().toString());
            throw new BaseException("内部服务调用出错");
        }
        return decoder.decode(response, type);
    }
}
